<?
// php-jquery-annotation
//
// by yinsee@wsatp.com
//
// hosted on google code
// http://code.google.com/p/php-jquery-annotations/

//error_reporting(E_ALL);
//ini_set('display_errors',1);

// change this if script path is not same as HTML, eg: /lib/
define(URL_PATH, '');

$mongo = new Mongo();
$db = $mongo->selectDB('mockup');
$db->notes->ensureIndex(array('url'=>1));
$count = 0;

if (isset($_POST['data'])) //save
{
   // the key is the referer URL
	$db->notes->remove(array('url'=>$_SERVER['HTTP_REFERER']));
	$obj['url'] = $_SERVER['HTTP_REFERER'];
	$obj['data'] = $_POST['data'];
	$db->notes->save($obj);
	print_r($obj);
	print "saved.";
	exit;
}
else
{
	// load
	$notes = $db->notes->findOne(array('url'=>$_SERVER['HTTP_REFERER']));
	print "var notes = ";
	print json_encode($notes['data']);
	print ";";
	$count = count($notes['data']);
}
// to add annotations
?>
var count = 0;
var have_run = false;
document.onready = function() {
	if (have_run) return;
	if (typeof(jQuery) == 'undefined') return;
	have_run = true;

	// start coding here
	$('#preview').click(function(e) { 
		if (!e.altKey) return;
		if (e.target.id!='preview') return;
		var msg = prompt('Enter comment');
		if (msg==undefined || msg=='') return;		
		e.stopPropagation();
		add_note(e, msg);
		save_notes();
	});
	$('.tip').live('click', function(e) { 
		if (!e.altKey) return;
		if (confirm('Remove note?')) {
			$(this).remove();
			renumber();
			save_notes();
		}
	});
	
	// restore the tags
	$.each(notes, function(el) {
		$('<div class=tip></div>').css({
			position: 'absolute',
			marginLeft: this.x,
			marginTop: this.y
		}).html(this.html).appendTo('#preview');
	});
	renumber();
};

function add_note(e,msg)
{
	count++;
	$('<div class=tip></div>').css({
		position: 'absolute',
		marginLeft: e.offsetX,
		marginTop: e.offsetY
	}).html('<span class=counter>'+count+'</span><span class=msg>'+msg+'</span>').appendTo('#preview');
}
function renumber()
{
	count = 0;
	$('.tip').each(function(){
		count++;
		$(this).find('.counter').remove();
		$('<span class=counter>'+count+'</span>').prependTo(this);
	});
}

function hide_notes()
{
	$('.tip').hide();
	$('#ann_toolbar').html('<a onclick="show_notes()">Show Notes</a>');
}
function show_notes()
{
	$('.tip').show();
	$('#ann_toolbar').html('<a onclick="hide_notes()">Hide Notes</a>');
}
function save_notes()
{
	var data = [];
	$('.tip').each(function(){ 
		var item = {};
		item.x = $(this).css('marginLeft');
		item.y = $(this).css('marginTop');
		item.html = $(this).html();
		data.push(item);
	});
	$.post('<?=URL_PATH?>annotate.php', { data: data } );
}
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js\"></scr" + "ipt>");
document.write("<link rel=\"stylesheet\" href=\"<?=URL_PATH?>annotate.css\"></script>");
document.write("<div id=ann_toolbar><a onclick=\"hide_notes()\">Hide Notes</a></div>");
